<template>
  <div class="app-container">
    <div class="filter-container">
      <p style="float:left;margin-top:5px;margin-left:2%">广告说明：</p>
      <el-input
        v-model="listQuery.name"
        size="small"
        placeholder="请输入广告说明"
        style="width: 200px;float:left"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <p style="float:left;margin-top:5px;margin-left:2%">广告状态：</p>
      <el-select
        size="small"
        placeholder="请选择状态"
        clearable
        class="filter-item"
        style="width: 200px;float:left"
        v-model="listQuery.status"
      >
        <el-option
          v-for="item in statusList"
          :key="item.key"
          :label="item.display_name"
          :value="item.key"
        />
      </el-select>

      <p style="float:left;margin-top:5px;margin-left:2%">发布时间：</p>
      <el-date-picker
        v-model="listQueryDate"
        size="small"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd HH:mm:ss"
      ></el-date-picker>
      <el-button
        size="small"
        class="filter-item"
        type="success"
        icon="el-icon-search"
        style="margin-left:3%"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        size="small"
        class="filter-item"
        style="margin-left: 10px;float:right"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      size="small"
      border
      fit
      highlight-current-row
      style="width: 100%;margin-top:1%"
    >
      <el-table-column type="index" label="序号"></el-table-column>
      <el-table-column label="广告说明" min-width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="主题图片" min-width="300px" align="center">
        <template slot-scope="scope">
          <img v-if="scope.row.imgUrl" :src="scope.row.imgUrl" style="width:300px;height:130px" alt />
        </template>
      </el-table-column>

      <el-table-column label="发布时间" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.pubTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="跳转方式" min-width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.refType=='propriceId'?'商品链接':scope.row.refType=='inLink'?'内部功能链接':scope.row.refType=='outLink'?'URL链接':'' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" min-width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.status==0?'下架':scope.row.status==1?'上架':scope.row.status==2?'待发布':''}}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        min-width="200px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button size="small" align="center" type="primary" @click="handleUpdate(row)">编辑</el-button>
          <el-button size="small" align="center" type="primary" @click="handleDel(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :close-on-click-modal="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      append-to-body
    >
      <el-form ref="dataForm" :model="temp" label-width="250px" label-position="right" style>
        <el-form-item label="广告说明：">
          <el-input v-model="temp.name" placeholder="输出广告说明" />
        </el-form-item>
        <el-form-item label="广告排序:">
          <el-input v-model="temp.sort" />
        </el-form-item>

        <el-form-item label="广告状态:">
          <el-select
            size="small"
            placeholder="选择上下架状态"
            clearable
            class="filter-item"
            style
            v-model="temp.status"
          >
            <el-option
              v-for="item in statusList"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="跳转方式:">
          <el-select
            size="small"
            placeholder="选择跳转方式"
            clearable
            class="filter-item"
            style
            v-model="temp.refType"
          >
            <el-option
              v-for="item in calendarTypeOptions"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="跳转功能页面:" v-if="temp.refType=='inLink'">
          <el-select
            size="small"
            placeholder="选择跳转页面"
            clearable
            class="filter-item"
            style
            v-model="temp.linkUrl"
          >
            <el-option v-for="item in inLinkList" :key="item.id" :label="item.k" :value="item.val" />
          </el-select>
        </el-form-item>

        <el-form-item label="跳转链接:" v-if="temp.refType=='outLink'">
          <el-input placeholder="请输入跳转链接" v-model="temp.linkUrl"></el-input>
        </el-form-item>

        <!-- <el-form-item label="跳转链接:" > -->
        <el-form-item label="商品ID(商品查询列表中获取):" v-if="temp.refType=='propriceId'">
          <el-input style="width:300px" v-model="temp.proId" />
          <el-button type="primary" style="margin-left:20px;" @click="queryGoods">查询商品</el-button>
        </el-form-item>

        <el-form-item label="商品名称:" v-if="checkProData.infoName&&temp.refType=='propriceId'">
          <el-input v-model="checkProData.infoName" disabled />
        </el-form-item>
        <el-form-item label="商品规格(不同价格)：" v-if="checkProData.list&&temp.refType=='propriceId'">
          <el-table
            :data="checkProData.list"
            tooltip-effect="dark"
            ref="tableData"
            @row-click="singleElection"
            stripe
            border
            style="width:100%"
          >
            <el-table-column label="单选" align="center">
              <template slot-scope="scope">
                <!-- <el-radio class="radio" v-model="checkPriceIndex" :label="scope.$index">&nbsp;</el-radio> -->
                <el-radio class="radio" v-model="checkPriceId" :label="scope.row.proPriceId">&nbsp;</el-radio>
              </template>
            </el-table-column>
            <el-table-column label="型号" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.proTitle}}</span>
              </template>
            </el-table-column>
            <el-table-column label="销售价格" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.proSellPrice/100}}</span>
              </template>
            </el-table-column>
            <el-table-column label="采购价格" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.purchansePrice/100}}</span>
              </template>
            </el-table-column>
            <el-table-column label="市场价格" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.proMarketPrice/100}}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <!-- </el-form-item> -->

        <el-form-item label="主题图片:">
          <el-upload
            class="avatar-uploader"
            action
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :http-request="customRequest"
          >
            <img
              style="width:100px;height:100px"
              v-if="temp.imgUrl"
              :src="temp.imgUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="发布时间:">
          <el-radio-group
            v-model="radio"
            @change="fabuDate"
            :disabled="dialogStatus == 'examine' ? true : false"
          >
            <el-radio :label="1">即时发布</el-radio>
            <el-radio :label="2">
              定时发布：
              <el-date-picker
                v-model="temp.pubTime"
                type="datetime"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">返回</el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 异步请求 delLly
import {
  headList,
  addHead,
  updateHead,
  deleteHead,
  getInLinkList
} from "../../../../api/appApi/headWheelReq.js";
import { queryGoods } from "@/api/activityManage";
import Vue from "vue";
import { addImg } from "@/api/headWheel";
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // 分页插件

const calendarTypeOptions = [
  {
    key: "propriceId",
    display_name: "商品链接"
  },
  {
    key: "inLink",
    display_name: "内部功能链接"
  },
  {
    key: "outLink",
    display_name: "URL链接"
  }
];
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});

export default {
  inject: ["reload"],
  components: {
    Pagination
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger"
      };
      return statusMap[status];
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    }
  },
  data() {
    return {
      radio: 1,
      sample: [],
      listQueryDate: [], //筛选时间
      deptValue: "",
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        status: "",
        sort: "+id"
      },
      growsIndex: "",
      temp: {
        id: undefined
      },
      dialogFormVisible: false,
      calendarTypeOptions,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "添加"
      },
      rowId: "",
      delId: "",
      changeRefType: "",
      statusList: [
        {
          key: "0",
          display_name: "下架"
        },
        {
          key: "1",
          display_name: "上架"
        },
        {
          key: "2",
          display_name: "待发布"
        }
      ],
      checkProData: {}, //根据id查询商品信息
      checkPriceId: "", //选中规格的id
      inLinkList: [] //功能list
    };
  },
  created() {
    this.getList();
    this.getInLinkList();
  },
  methods: {
    fabuDate() {
      console.log(this.radio);
      if (this.radio === 1) {
        this.temp.pubTime = "";
      } else if (this.radio === 2) {
        return this.temp.pubTime;
      }
    },
    handleAvatarSuccess(res, file) {
      this.temp.imgUrl = URL.createObjectURL(file.raw);
      console.log("11");
    },

    customRequest(data) {
      const formData = new FormData();
      formData.append("file", data.file);
      this.saveFile(formData);
    },
    saveFile(formData) {
      addImg(formData).then(res => {
        // this.imageUrl=res.data
        // this.temp.imgUrl = res.data.filePath
        this.$set(this.temp, "imgUrl", res.data.filePath);
        console.log(this.temp);
      });
    },

    // 获取内部链接list
    getInLinkList() {
      let formdata = {
        type: "inLink"
      };
      getInLinkList(formdata).then(res => {
        console.log("inlink", res.data);
        this.inLinkList = res.data;
      });
    },

    // 获取list
    getList() {
      this.listLoading = true;
      var params = Object.assign({}, this.listQuery);
      params.pageNum = this.listQuery.pageNum - 1;
      params.pubAddr = "firstPage";
      params.showChannel = "SHOP_KEEPER";
      params.startTime = this.listQueryDate[0];
      params.endTime = this.listQueryDate[1];
      // var params = {
      //   // pageConvert: true,
      //   pageNum: this.listQuery.pageNum - 1,
      //   pageSize: this.listQuery.pageSize,
      //   pubAddr: "firstPage",
      //   showChannel: "SHOP_KEEPER"
      // };
      headList(params).then(response => {
        this.list = response.data.content;
        this.total = response.data.totalElements;
        this.listLoading = false;
      });
    },

    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },

    // 初始化temp
    resetTemp() {
      this.temp = {
        id: undefined
      };
      console.log(this.temp);
      this.checkProData = {};
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = "update";
      this.dialogFormVisible = true;

      if (this.temp.refType == "propriceId") {
        var idList = this.temp.refId.split(",");
        // this.temp.proId =
        this.temp.proPriceId = idList[2];
        this.temp.proInfoId = idList[1];
        this.checkPriceId = idList[2];
        this.$set(this.temp, "proId", idList[0]);
        this.queryGoods();
      }
      console.log("bj", this.temp);
      console.log("bj", row);

      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },

    // 根据商品id查询商品
    queryGoods() {
      this.checkProData = {};
      queryGoods(this.temp.proId).then(res => {
        console.log(res);
        if (res.code == "200") {
          if (res.data.infoName) {
            this.checkProData = res.data;
          } else {
            this.$notify({
              title: "失败",
              message: "未查到商品",
              type: "danger",
              duration: 2000
            });
          }
        } else {
          this.$notify({
            title: "失败",
            message: res.error_msg,
            type: "danger",
            duration: 2000
          });
        }
      });
    },

    //选择规格
    singleElection(item) {
      console.log(item);
      this.temp.proPriceId = item.proPriceId;
      this.temp.proInfoId = item.proInfoId;
      this.checkPriceId = item.proPriceId;
    },

    handleDel(row) {
      this.$confirm("确定删除？ 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
        .then(async () => {
          console.log(row);
          deleteHead(row.id).then(result => {
            if (result.code === "200") {
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success"
              });
              this.getList();
            } else {
              this.$notify({
                title: "失败",
                message: res.error_msg,
                type: "danger"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    // 修改轮播图
    updateData() {
      const tempData = Object.assign({}, this.temp);
      console.log("bj", tempData);
      // if (tempData.pubTime) {
      //   let pubTime = new Date(tempData.pubTime).getTime()
      //   tempData.pubTime = pubTime
      // }

      updateHead(tempData).then(res => {
        this.dialogFormVisible = false;
        console.log(res);
        if (res.code == "200") {
          this.$notify({
            title: "成功",
            message: "修改成功",
            type: "success",
            duration: 2000
          });
          this.getList();
        } else {
          this.$notify({
            title: "失败",
            message: res.error_msg,
            type: "danger",
            duration: 2000
          });
        }
      });
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      this.temp.pubAddr = "firstPage";
      this.temp.showChannel = "SHOP_KEEPER";
      let formdata = {};

      for (var attr in this.temp) {
        formdata[attr] = this.temp[attr];
      }
      // if (formdata.pubTime) {
      //   let pubTime = new Date(formdata.pubTime).getTime()
      //   formdata.pubTime = pubTime

      // }
      // console.log(this.temp)

      if (formdata.refType == "propriceId") {
        formdata.refId =
          formdata.proId + "," + formdata.proInfoId + "," + formdata.proPriceId;
      }
      console.log(formdata);

      addHead(formdata).then(res => {
        this.dialogFormVisible = false;
        console.log(res);
        if (res.code == "200") {
          this.$notify({
            title: "成功",
            message: "添加成功",
            type: "success",
            duration: 2000
          });
          this.getList();
          this.checkProData = "";
        } else {
          this.$notify({
            title: "失败",
            message: res.error_msg,
            type: "danger",
            duration: 2000
          });
        }
      });
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}`
        ? "ascending"
        : sort === `-${key}`
        ? "descending"
        : "";
    }
  }
};
</script>
<style scoped>
.avatar-uploader >>> .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
